import { createRouter, createWebHashHistory } from "vue-router";
import routes from "./routes";
import store from "../store";
import NProgress from "nprogress";
import "nprogress/nprogress.css";

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

//页面白名单name
const whiteList = ["Login", "NotFound", "My"];

router.beforeEach((to, from, next) => {
  NProgress.start();
  const userInfo = store.getters.userInfo;
  const user = JSON.parse(localStorage.getItem("userInfo"));
  //判断该路由是否需要验证
  if (to.meta.checking) {
    //判断是否登录或者登录过期
    if (user && userInfo) {
      //该页面是否需要超级管理员权限
      if (to.meta.isSuper) {
        //判断该用户是否有权限
        if (user.super && userInfo.super) {
          ElMessage.success(`已进入${to.name}`);
          next();
          NProgress.done();
        } else {
          //没有该页面权限
          ElMessage.error("您暂无权限，请联系管理员处理");
          next(from.path);
          return NProgress.done();
        }
      } else {
        //该不需要超级管理员权限
        next();
        NProgress.done();
      }
    } else {
      //登录过期或未登录
      ElMessage.warning("请登录");
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    }
  } else {
    //无需鉴权判断该页面是否可以直接进入
    if (whiteList.includes(to.name)) {
      if (to.name === "Login") {
        if (userInfo && user) {
          next("/");
          return NProgress.done();
        }
      }
      next();
      NProgress.done();
    } else {
      ElMessage.warning("请登录");
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    }
  }
});
router.afterEach(() => {
  NProgress.done();
});

export default router;
